package com.gable.exhibition.websocket;

import com.alibaba.fastjson.JSON;
import com.gable.exhibition.view.SocketMessageView;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.*;

/**
 * Created by Lesson on 2018/2/27.
 */
public class WSHandler implements WebSocketHandler {

    Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private WSClientManager wsClientManager;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        try {
            logger.debug("connect to the websocket success......");
            SocketMessageView sw = new SocketMessageView();
            sw.setMessageType("head");
            sw.setMessage("连接成功");
            String message = JSON.toJSONString(sw);
            session.sendMessage(new TextMessage(message));
            wsClientManager.setWSS.add(session);
        }catch (Exception e){

        }
    }

    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) {
       try {
           TextMessage returnMessage = new TextMessage(webSocketMessage.getPayload()
                   + " received at server");
           logger.debug(webSocketSession.getHandshakeHeaders().getFirst("Cookie"));
           webSocketSession.sendMessage(returnMessage);
       }catch (Exception e){

       }
    }

    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) {
        try {
            if (webSocketSession.isOpen()) {
                webSocketSession.close();
                wsClientManager.setWSS.remove(webSocketSession);
            }
            logger.debug("websocket connection closed......");
        }catch (Exception e){

            }
        }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) {
            try {
                logger.debug("websocket connection closed......");
                wsClientManager.setWSS.remove(webSocketSession);
            }catch (Exception e){

            }
        }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
